/**
 * Copyright (c) 2015-2017, Javen Zhou  (javen205@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

package com.javen.weixin.controller;

import java.util.ArrayList;
import java.util.List;

import com.javen.weixin.Interceptor.ConfigInterceptor;
import com.javen.weixin.common.model.Config;
import com.javen.weixin.common.model.Keyword;
import com.javen.weixin.common.model.Material;
import com.javen.weixin.common.model.Submsg;
import com.javen.weixin.common.model.User;
import com.javen.weixin.kit.URLCodeKit;
import com.javen.weixin.service.KeyWordService;
import com.javen.weixin.service.MaterialService;
import com.javen.weixin.service.SubMsgService;
import com.javen.weixin.service.WxUserService;
import com.javen.weixin.utils.RedPackUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.CustomServiceApi;
import com.jfinal.weixin.sdk.api.UserApi;
import com.jfinal.weixin.sdk.jfinal.MsgControllerAdapter;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InLocationEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.InQrCodeEvent;
import com.jfinal.weixin.sdk.msg.out.News;
import com.jfinal.weixin.sdk.msg.out.OutNewsMsg;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;

/**
 * @author Javen 
 * 2017年6月11日
 */
@Before(ConfigInterceptor.class)
public class WeiXinMsgController extends MsgControllerAdapter {

	static Log logger = Log.getLog(WeiXinMsgController.class);
	private static final String helpStr = "\t你的品位不错哦  么么哒 -By Javen。";

	static KeyWordService kws = KeyWordService.me;
	static SubMsgService subs = SubMsgService.me;
	static MaterialService materials = MaterialService.me;
	static WxUserService wxus = WxUserService.me;

	/**
	 * 接收文本消息事件
	 */
	@Override
	protected void processInTextMsg(InTextMsg inTextMsg) {
		String msgContent = inTextMsg.getContent().trim();
		final String openId = inTextMsg.getFromUserName();
		// String rmid = getPara("rmid");//再通过rmid 查询APPId,这里为了方便直接将其存入session
		final Config config = (Config) getSession().getAttribute("config");
		logger.info(config.toJson());
		Keyword keyword = kws.getFirstKW(config.getAppId(), msgContent);
		logger.info("keyword>" + JsonKit.toJson(keyword));
		if (null != keyword) {
			String content = keyword.getContent();
			Integer type = keyword.getType();
			if (type == 1) {
				renderOutTextMsg(content);
				return;
			} else if (type == 2) {
				// 通过关键字查询图文
				OutNewsMsg outMsg = new OutNewsMsg(inTextMsg);
				List<News> news = getNews(config.getAppId(), content);
				outMsg.setArticles(news);
				render(outMsg);
				return;
			}
		}
		if (msgContent.equals("红包")) {
			new Thread(new Runnable() {
				public void run() {
					logger.info("是发红包的时候了...");
					RedPackUtil.sendRedPack(config, 1, openId, IpKit.getRealIp(getRequest()));
				}
			}).start();
			renderNull();
			return;
		}
		renderOutTextMsg(msgContent);
	}

	/**
	 * 关注/取消关注事件
	 */
	@Override
	protected void processInFollowEvent(final InFollowEvent inFollowEvent) {
		if (InFollowEvent.EVENT_INFOLLOW_SUBSCRIBE.equals(inFollowEvent.getEvent())) {
			final Config config = (Config) getSession().getAttribute("config");
			final String openId = inFollowEvent.getFromUserName();
			String appId = config.getAppId();
			logger.info("关注：" + openId);
			//获取用户基本信息(UnionID机制)
			ApiResult userInfo = UserApi.getUserInfo(openId);
			System.out.println("userInfo>"+userInfo.getJson());
			if (userInfo.isSucceed()) {
				try {
					final User user = wxus.toSave(appId, userInfo);
					new Thread(new Runnable() {
						
						@Override
						public void run() {
							//客服接口发送异步消息
							StringBuffer sbf = new StringBuffer();
							sbf.append("欢迎").append("【").append(URLCodeKit.decode(user.getNickName()))
							.append("】").append("关注。");
							CustomServiceApi.sendText(openId, sbf.toString());
						}
					}).start();
				} catch (Exception e) {
					logger.error(e.getMessage());
				}
			}
			
			final Submsg submsg = subs.getSubMsgByAppId(config.getAppId());
			logger.info("submsg：" + JsonKit.toJson(submsg));
			// 异步判断是否需要发红包
			new Thread(new Runnable() {

				@Override
				public void run() {
					// 判断是否需要发红包
					Integer readpackId = submsg.getRedpackId();
					logger.info("readpackId>" + readpackId);
					RedPackUtil.sendRedPack(config, readpackId, inFollowEvent.getFromUserName(),
							IpKit.getRealIp(getRequest()));
				}
			}).start();

			// 如果关注回复消息不为空
			if (null != submsg) {
				Integer type = submsg.getType();
				if (type == 0) {
					renderOutTextMsg(submsg.getContent());
					return;
				} else if (type == 1) {
					// 图文 通过文章的关键字查询回复的图文
					String articleKey = submsg.getArticleKey().trim();
					logger.info("articleKey>" + articleKey);
					OutNewsMsg outMsg = new OutNewsMsg(inFollowEvent);
					List<News> news = getNews(config.getAppId(), articleKey);
					outMsg.setArticles(news);
					render(outMsg);
					return;
				} else if (type == 2) {
					// 图片
				}
			}

			OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
			outMsg.setContent(helpStr);
			render(outMsg);
		}
		// 如果为取消关注事件，将无法接收到传回的信息
		if (InFollowEvent.EVENT_INFOLLOW_UNSUBSCRIBE.equals(inFollowEvent.getEvent())) {
			logger.debug("取消关注：" + inFollowEvent.getFromUserName());
			renderNull();
		}
	}

	/**
	 * 自定义菜单事件
	 */
	@Override
	protected void processInMenuEvent(InMenuEvent inMenuEvent) {
		StringBuffer sbf = new StringBuffer();
		sbf.append("事件类型：").append(inMenuEvent.getEvent()).append("\n").append("消息类型：").append(inMenuEvent.getMsgType())
				.append("\n")

				// sbf.append("扫码内容：").append(inMenuEvent.getScanCodeInfo().getScanResult()).append("\n")

				.append("openId：").append(inMenuEvent.getFromUserName()).append("\n").append("事件Key：")
				.append(inMenuEvent.getEventKey()).append("\n");
		renderOutTextMsg(sbf.toString());
	}

	@Override
	protected void processInQrCodeEvent(InQrCodeEvent inQrCodeEvent) {
		System.out.println("扫码.......");
		if (InQrCodeEvent.EVENT_INQRCODE_SUBSCRIBE.equals(inQrCodeEvent.getEvent())) {
			logger.debug("扫码未关注：" + inQrCodeEvent.getFromUserName());
			OutTextMsg outMsg = new OutTextMsg(inQrCodeEvent);
			outMsg.setContent("感谢您的关注，二维码内容：" + inQrCodeEvent.getEventKey());
			render(outMsg);
		}
		if (InQrCodeEvent.EVENT_INQRCODE_SCAN.equals(inQrCodeEvent.getEvent())) {
			logger.debug("扫码已关注：" + inQrCodeEvent.getFromUserName());
			renderOutTextMsg("扫码已关注,二维码内容：" + inQrCodeEvent.getEventKey());
		}

	}

	@Override
	protected void processInLocationEvent(InLocationEvent inLocationEvent) {
		logger.debug("发送地理位置事件：" + inLocationEvent.getFromUserName());
		OutTextMsg outMsg = new OutTextMsg(inLocationEvent);
		outMsg.setContent("地理位置是：" + inLocationEvent.getLatitude());
		render(outMsg);
	}

	public void renderOutTextMsg(String content) {
		OutTextMsg outMsg = new OutTextMsg(getInMsg());
		outMsg.setContent(content);
		render(outMsg);
	}

	/**
	 * 根据AppId 以及 文件key查询图文
	 * 
	 * @param appId
	 * @param article_key
	 * @return
	 */
	public static List<News> getNews(String appId, String article_key) {
		List<News> articles = null;
		List<Material> list = materials.getMaterialBySKI(appId, article_key);
		logger.info("material list>" + JsonKit.toJson(list));
		if (null != list && list.size() > 0) {
			articles = new ArrayList<News>();
			for (Material material : list) {
				News news = new News();
				news.setTitle(material.getTitle());
				String url = material.getUrl();
				if (StrKit.notBlank(url)) {
					news.setUrl(url);
				} else {
					news.setUrl(PropKit.get("domain") + "/material/getById?id=" + material.getId());
				}
				news.setPicUrl(material.getImageUrl());
				news.setDescription(material.getDescribe());
				articles.add(news);
			}
		}
		return articles;
	}

}
